﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MapReduce.Comm
{
    public class JobCallbackPool
    {
        private static Object mLock = new Object();
        private static Dictionary<String, JobRequest.Callback> mPool = new Dictionary<string, JobRequest.Callback>();

        public static String Lock(String pSlaveAddress, ushort pPort, JobRequest.Callback pCallback)
        {
            lock (mLock)
            {
                String id = pSlaveAddress + pPort + Guid.NewGuid().ToString();
                mPool[id] = pCallback;

                return id;
            }
        }

        public static void ReleaseSlave(String pSlaveAddress, ushort pPort)
        {
            lock (mLock)
            {
                String partid = pSlaveAddress + pPort;

                List<String> removeids = new List<string>();
                foreach (KeyValuePair<String, JobRequest.Callback> pair in mPool)
                {
                    if (pair.Key.StartsWith(partid))
                    {
                        removeids.Add(pair.Key);
                    }
                }//foreach mPool

                foreach (String id in removeids)
                {
                    mPool.Remove(id);
                }
            }

        }//ReleaseSlave

        public static JobRequest.Callback Release(String pId)
        {
            lock (mLock)
            {
                JobRequest.Callback callback = mPool[pId];
                mPool.Remove(pId);
                return callback;
            }
        }

    }//JobCallbackPool
}
